
import {Base64} from 'js-base64'

class Utils {
    constructor() {
        this.currency = {
            "CN": "￥",
            "US": "$"
        }
        this.buy_time = [
            {
                str: '月底',
                month: 1
            },
            {
                str: '1个月',
                month: 1
            },
            {
                str: '2个月',
                month: 2
            },
            {
                str: '3个月',
                month: 3
            },
            {
                str: '4个月',
                month: 4
            },
            {
                str: '5个月',
                month: 5
            },
            {
                str: '6个月',
                month: 6
            },
            {
                str: '7个月',
                month: 7
            },
            {
                str: '8个月',
                month: 8
            },
            {
                str: '9个月',
                month: 9
            },
            {
                str: '10个月',
                month: 10
            },
            {
                str: '11个月',
                month: 11
            },
            {
                str: '12个月',
                month: 12
            },
            {
                str: '2年',
                month: 24
            },
            {
                str: '3年',
                month: 36
            }
        ]
        this.newDate = new Date()
        this.nowDay = this.newDate.getDate()
        this.nowMonth = this.newDate.getMonth()
        this.nowYear = this.newDate.getFullYear()
    }

    changeCurrency(area_id) {
        return this.currency[area_id] || this.currency.CN
    }

    changeBuyTime(timeString, monthNum) {
        console.log(timeString)
        if (timeString) {
            if (timeString === '月底') {
                return {
                    month: 1
                }
            } else {
                let month
                this.buy_time.map(item => {
                    if (item.str === timeString) {
                        month = item.month
                    }
                })
                return {
                    month
                }
            }
        }
        if (monthNum) {
            let str
            if (monthNum == '1') {
                str = '1个月'
            } else {
                this.buy_time.map(item => {
                    if (item.month === monthNum) {
                        str = item.str
                    }
                })
            }
            return {
                str
            }
        }
    }

    getChangeBuyTimeExpire(month = 1, isEndToMonth, start_time) {
        if (isEndToMonth) {
            return this.formatDate(new Date(this.nowYear, this.nowMonth + 1, 1))
        }
        // const date = new Date()
        // date.setMonth(this.nowMonth + month)
        const expireDate = this.formatDate(this.FnEndTime(month, start_time))
        console.log(345236345, expireDate)
        return expireDate
    }

    FnEndTime(num, time) {
        let _nowDate = time ? new Date(time) : new Date()
        let _oldYear = _nowDate.getFullYear()
        let _oldMonth = _nowDate.getMonth() + 1
        let _oldDay = _nowDate.getDate()
        let _oldHour = _nowDate.getHours()
        let _oldMinute = _nowDate.getMinutes()
        let _addMonth = _oldMonth + num
        let _year = parseInt(_addMonth / 12)
        let _month = _addMonth % 12
        let _newMonth = _addMonth % 12
        _newMonth = _newMonth === 0 ? 12 : _newMonth

        let _newYear = _month === 0 ? _oldYear : _oldYear + _year
        let _newHour = '00'
        let _newMinute = '00'

        if (_oldMonth === 12 && _month === 0) {
            _newYear = _oldYear + (_year - 1)
        }
        let _newDay = ''
        // var maxMonthDay = '
        let endDateDay = new Date(_newYear, _newMonth, 0).getDate()
        let maxMonthDay = endDateDay
        if (_oldDay > maxMonthDay) {   // 判断到期月份最大的天数是几号，如果31号开通，但到期月最大日期是30号，则显示到30号到期
            _newDay = maxMonthDay
        } else {
            _newDay = _oldDay
        }
        _newHour = _oldHour
        _newMinute = _oldMinute
        if (_newMinute < 10 && _newMinute != '00') {
            _newMinute = '0' + _newMinute
        }
        return _newYear + '-' + _newMonth + '-' + _newDay + ' ' + _newHour + ':' + _newMinute
    }

    getMonthDay(nowMonth) {
        const monthStartDay = new Date(this.nowYear, nowMonth, 1)
        const monthEndDate = new Date(this.nowYear, nowMonth + 1, 1)
        const days = (monthEndDate - monthStartDay) / (1000 * 60 * 60 * 24)
        return days
    }

    formatDate(date, fmt) {
        // "yyyy-MM-dd hh:mm:ss"
        fmt = fmt || "yyyy-MM-dd hh:mm:ss"
        date = new Date(date)
        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
        }
        let o = {
            'M+': date.getMonth() + 1,
            'd+': date.getDate(),
            'h+': date.getHours(),
            'm+': date.getMinutes(),
            's+': date.getSeconds()
        };
        for (let k in o) {
            if (new RegExp(`(${k})`).test(fmt)) {
                let str = o[k] + '';
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : this.padLeftZero(str));
            }
        }
        return fmt;
    }

    padLeftZero(str) {
        return ('00' + str).substr(str.length);
    }

    getQueryString(name) {
        let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        let r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    }

    // 计算两个日期之间相差几个月【按月份计算】
    getBetweenMonths(beginDate, endDate) {
        let number = 0;
        let yearToMonth = (endDate.getFullYear() - beginDate.getFullYear()) * 12
        number += yearToMonth;
        let monthToMonth = endDate.getMonth() - beginDate.getMonth();
        number += monthToMonth;
        return parseInt(number)
    }

    // 计算两个日期之间相差几个月【按天数计算，月数取整】
    getBetweenMonthsByDay(beginDate, endDate) {
        let begin = new Date(beginDate).getTime()
        let end = new Date(endDate).getTime()
        let day_num = (end - begin) / (1000 * 60 * 60 * 24) - 1 //相差天数
        let now_month = new Date().getMonth() + 1
        if (28 <= day_num && day_num < 30) {
            if (now_month == 2) {
                return 1
            } else {
                return -1
            }
        } else if (day_num < 28) {
            //小于28天，返回-1
            return -1
        } else {
            return parseInt(day_num / 30)
        }
    }

    getStrBytes(str) {
        if (str == null || str === undefined) return 0;
        if (typeof str != "string") {
            return 0;
        }
        var total = 0, charCode, i, len;
        for (i = 0, len = str.length; i < len; i++) {
            charCode = str.charCodeAt(i);
            if (charCode <= 0x007f) {
                total += 1;//字符代码在000000 – 00007F之间的，用一个字节编码
            } else if (charCode <= 0x07ff) {
                total += 2;//000080 – 0007FF之间的字符用两个字节
            } else if (charCode <= 0xffff) {
                total += 3;//000800 – 00D7FF 和 00E000 – 00FFFF之间的用三个字节，注: Unicode在范围 D800-DFFF 中不存在任何字符
            } else {
                total += 4;//010000 – 10FFFF之间的用4个字节
            }
        }
        return total;
    }

    isBase64(str) {
        if (str === '' || str.trim() === '') {
            return false;
        }
        try {
            let b64 = Base64.decode(str) //解码
            return Base64.encode(b64) == str;
        } catch (err) {
            return false;
        }
    }

    //计费为包年包月时， 根据滑块的值计算正确的月份数【系统默认是[0,14],最大为3年（36个月）】
    fnSliderTime(data) {
        let time = data
        if (data === 13) {
            time = 24
        } else if (data === 14) {
            time = 36
        }
        return time
    }

    isBase64New(str) {
        if (str === '' || str.trim() === '') {
            return false;
        }
        try {
            return btoa(atob(str)) == str
        } catch (err) {
            try {
                return Base64.encode(Base64.decode(str)) == str;
            }catch (err){
                return false;
            }

        }
    }
}

export default new Utils()
